package com.project_test.kun.travelling_1st.Utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.util.LruCache;

import com.android.volley.Cache;
import com.android.volley.Network;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HttpStack;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.ImageLoader;

import java.io.File;

/**
 * Created by asus on 2016/10/18 16 49.
 * 邮箱:763433963@qq.com
 */
public class CustomVolley {

    //私有构造方法，公有的访问方法

    public static RequestQueue sRequestQueue;

    //如果有大量图片下载需求，用imageLoader

    public static ImageLoader sImageLoader;

    private static CustomVolley ourInstance;

    public static CustomVolley getInstance(Context context) {
        if (ourInstance == null) {
            synchronized (CustomVolley.class) {
                if (ourInstance == null) {
                    ourInstance = new CustomVolley(context);
                }
            }

        }
        return ourInstance;
    }

    private CustomVolley(Context context) {
        Cache cache = getCache(context);
        Network network = getNetwork();
        sRequestQueue = new RequestQueue(cache, network, 6);
        sRequestQueue.start();

        ImageLoader.ImageCache imageCache = getImageCache();
        sImageLoader = new ImageLoader(sRequestQueue, imageCache);


    }

    private ImageLoader.ImageCache getImageCache() {
        ImageLoader.ImageCache imageCache = new ImageLoader.ImageCache() {
            public int maxSize = (int) (Runtime.getRuntime().totalMemory() / 8);
            LruCache<String, Bitmap> cache = new LruCache<>(maxSize);


            @Override
            public Bitmap getBitmap(String url) {

                return cache.get(url);
            }

            @Override
            public void putBitmap(String url, Bitmap bitmap) {
                cache.put(url, bitmap);
            }
        };

        return imageCache;
    }

    private Network getNetwork() {
        HttpStack httpStack = new HurlStack();
        Network network = new BasicNetwork(httpStack);
        return network;
    }

    private Cache getCache(Context context) {
        File dir = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        } else {
            dir = context.getCacheDir();
        }

        File rootDirection = new File(dir, "volley");
        if (!rootDirection.exists()) {
            rootDirection.mkdirs();
        }
        Cache cache = new DiskBasedCache(rootDirection, 100 * 1024 * 1024);//最好代码重构

        return cache;

    }


}
